Kernel.extend(Kernel, {
		
	doREST: function(config) {
		config.dataType = 'json';
		this.doAjax(config);
	},
	
	doAjax: function(config) {
		$.ajax({
			url: 'ajax.php/'+config.url,
			type: config.type,
			data: config.params,
			dataType: config.dataType,
			success: config.success,
			error: function(jqXHR, textStatus, errorThrown) {
				if (config.failure) {
					config.failure('Ajax call failed.');
				}
			}
		});
	},
	
	render: function(instance) {
		if (instance.widget) {
			this.renderWidget(instance)
		}
		else {
			this.renderModule(instance)
		}
	},
	
	renderWidget: function(instance) {
		// Wrap the module in a widget render to mini canvas
		// $.get('widgets/'+instance.title+'/'+instance.file, function(data) {
		//	$(instance.renderTo).html(data+"");
			
			// Save reference to module element for later
			instance.$moduleEl = $('#'+instance.id);
			
			// Make sure to finally call init()
			instance.init();
		//});
	},
	
	renderModule: function(instance) {
		var isRunning = $('#fsa-'+instance.title).length;

		if (Kernel.sandbox.mRunningTitle !== instance.title) {
			if (isRunning == 0) {
				// render to full screen canvas
				$.get('modules/'+instance.title+'/'+instance.file, function(data) {
					$('body').append("<div id='fsa-"+instance.title+"' style='display:none; top: -520px; width: 100%; height: 500px; color: #000;'>"+data+"</div>");
	
					if (Kernel.sandbox.mRunningFSA) {
						$( Kernel.sandbox.mRunningFSA ).hide('slide');
					} else {
						$( "#mainPage" ).hide('slide');
					}
					$( "#fsa-"+instance.title ).toggle('fade', 500);
	
					// Save reference to module element for later
					instance.$moduleEl = $(instance.renderTo);
	
					Kernel.sandbox.mRunningTitle = instance.title;
					Kernel.sandbox.mRunningFSA = "#fsa-"+instance.title;
			
					// Make sure to finally call init()
					instance.init();
				});		
			} else {
				if (Kernel.sandbox.mRunningFSA) {
					$( Kernel.sandbox.mRunningFSA ).hide('slide');
				} else {
					$( "#mainPage" ).hide('slide');
				}
				$( "#fsa-"+instance.title ).toggle('fade', 500);
	
				Kernel.sandbox.mRunningTitle = instance.title;
				Kernel.sandbox.mRunningFSA = "#fsa-"+instance.title;
			}
		}
	},

	// Highjacking the startup gives you control over when module.init() gets called
	onStart: function(instance) {
		if (instance.file) {
			this.render(instance);
		}
		else {
			instance.init();
		}
	},
	
	onStop: function(instance) {
		
		// Allow module to handle its own shutdown first
		instance.kill();
		
		// Take care of any rendered elements
		var el = instance.$moduleEl;
	
		if (el) {
			el.fadeOut(500, function()
			{
				el.remove();
			});
		}
	}
});
